package com.wang.hello.qrcode;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public class QrCode implements Barcode{
	public transient final Log logger = LogFactory.getLog(getClass());
	
	private int defaultWidth = 256;
	private int defaultHeight = 256;
	
	public QrCode(){}
	
	public QrCode(int width, int height)
	{
		defaultWidth = width;
		defaultHeight = height;
	}

	public void encoder(OutputStream outputStream, String code) throws RuntimeException
	{
		Map<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        
		MultiFormatWriter writer = new MultiFormatWriter();
		
		BitMatrix matrix = null;
		
		try {
			matrix = writer.encode(code, BarcodeFormat.QR_CODE, defaultWidth, defaultHeight, hints);
		} catch (WriterException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
		
		if(null != matrix)
		{
			BufferedImage image = new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB);
			for (int i = 0; i < matrix.getHeight(); i++)
			{
				for (int j = 0; j < matrix.getWidth(); j++)
				{
					image.setRGB(i, j, (matrix.get(i, j) ? 0 : 0xFFFFFF));
				}
			}
			
			try {
				ImageIO.write(image, "png", outputStream);
			} 
			catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new RuntimeException(e);
			}
		}
	}
}
